﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DLULearningNetwork.Libs;
using DLULearningNetworkModel;
using DLULearningNetwork.ViewModels;
using System.Web.Script.Serialization;
using System.IO;
using DLULearningNetwork.ActionFilterAttributes;
using System.Web.Helpers;
namespace DLULearningNetwork.Controllers
{
    public class ProfileController : Controller
    {
        [RequireUserLogin()]
        public ActionResult Edit()
        {

            return View();
        }
        [RequireUserLogin()]
        public PartialViewResult BasicInfo()
        {
            //Lay current user
            Account curUser = (Account)LibSession.Get(Constants.ACCOUNT_LOGIN);
            ViewBag.LstSecurityQuestion = SecurityQuestions.All();
            //Gan thong tin chinh sua vao basic info
            BasicInfoViewModel basicInfoVM = new BasicInfoViewModel();
            basicInfoVM.FirstName = curUser.FirstName_s;
            basicInfoVM.LastName = curUser.LastName_s;
            basicInfoVM.DateOfBirth = curUser.DateOfBirth_dt.Day +"/"+curUser.DateOfBirth_dt.Month+"/"+ curUser.DateOfBirth_dt.Year;
            basicInfoVM.SecurityQuestion = curUser.SecurityQuestionID_u.ToString();
            basicInfoVM.SecurityAnswer = curUser.Answer_s;
            basicInfoVM.Sex = curUser.Sex_b;
            return PartialView(basicInfoVM);
        }
        [HttpPost]
        [RequireUserLogin()]
        public PartialViewResult SavingBasicInfo(BasicInfoViewModel basicInfo)
        {
            //Undone : chua hien thi thong bao thanh cong
            ViewBag.LstSecurityQuestion = SecurityQuestions.All();
            if (ModelState.IsValid)
            {
                Account acc = RequireUserLogin.LoginUser;
                acc.FirstName_s = basicInfo.FirstName;
                acc.LastName_s = basicInfo.LastName;
                string[] ds = basicInfo.DateOfBirth.Split(new char[1]{'/'});
                acc.DateOfBirth_dt = DateTime.Parse(ds[1]+"/"+ds[0]+"/"+ds[2]);
                acc.SecurityQuestionID_u = Guid.Parse(basicInfo.SecurityQuestion);
                acc.Answer_s = basicInfo.SecurityAnswer;
                acc.Sex_b = basicInfo.Sex;
                acc = Account.UpdateBasicInfo(acc);
                if (acc != null)
                {
                    LibSession.Set(Constants.ACCOUNT_LOGIN, acc);
                    ViewBag.Success = true;
                }
                else
                {
                    ViewBag.Success = false;
                }
            }
            return PartialView("BasicInfo", basicInfo);
        }
        [RequireUserLogin()]
        public PartialViewResult ContactInfo()
        {
            Account curUser = LibSession.Get(Constants.ACCOUNT_LOGIN) as Account;

            Profile profile = Profile.Single(curUser.AccountID_u);

            ContactInfoViewModel contactInfoVM = new ContactInfoViewModel();

            if (profile != null)
            {
                contactInfoVM.IMAOL = profile.IMAOL_s == null ? "" : profile.IMAOL_s;
                contactInfoVM.IMGTalk = profile.IMGTalk_s == null ? "" : profile.IMGTalk_s;
                contactInfoVM.IMMSN = profile.IMMSN_s == null ? "" : profile.IMMSN_s;
                contactInfoVM.IMSkype = profile.IMSkype_s == null ? "" : profile.IMSkype_s;
                contactInfoVM.IMYahoo = profile.IMYahoo_s == null ? "" : profile.IMYahoo_s;
            }

            return PartialView(contactInfoVM);
        }

        [HttpPost]
        [RequireUserLogin()]
        public PartialViewResult SavingContactInfo(ContactInfoViewModel contactInfo)
        {
            if (ModelState.IsValid)
            {
                bool hasUpdate = false;
                //Cập nhật tại bước này
                Account curUser = RequireUserLogin.LoginUser;
                Profile pf = Profile.Single(curUser.AccountID_u);
                if (contactInfo.IMYahoo != null)
                {
                    pf.IMYahoo_s = contactInfo.IMYahoo;
                    hasUpdate = true;
                }
                if (contactInfo.IMSkype != null)
                {
                    pf.IMSkype_s = contactInfo.IMSkype;
                    hasUpdate = true;
                }
                if (contactInfo.IMMSN != null)
                {
                    pf.IMMSN_s = contactInfo.IMMSN;
                    hasUpdate = true;
                }
                if (contactInfo.IMGTalk != null)
                {
                    pf.IMGTalk_s = contactInfo.IMGTalk;
                    hasUpdate = true;
                }
                if (contactInfo.IMAOL != null)
                {
                    pf.IMAOL_s = contactInfo.IMAOL;
                    hasUpdate = true;
                }
                if (hasUpdate)
                {
                    if (Profile.Update(pf) > 0)
                    {
                        ViewBag.Success = true;
                        return PartialView("ContactInfo", contactInfo);
                    }
                    else
                    {
                        ViewBag.Success = false;
                    }
                }
                ViewBag.Success = false;
            }
            return PartialView("ContactInfo", contactInfo);
        }

        [RequireUserLogin()]
        public PartialViewResult EducationInfo()
        {
            Account user = (Account)LibSession.Get(Constants.ACCOUNT_LOGIN);
            Profile profile = Profile.Single(user.AccountID_u);
            List<ProfileAttribute> lstProfileAttribute = ProfileAttribute.SelectByProfileIdAndAttributeType(profile.ProfileID_u, EnumAttributeType.EducationInfo.ToString());
            List<EducationInfoViewModel> lstEducationInfo = new List<EducationInfoViewModel>();
            EducationInfoViewModel educationInfo;
            foreach (ProfileAttribute pa in lstProfileAttribute)
            {
                JavaScriptSerializer sr = new JavaScriptSerializer();
                educationInfo = (EducationInfoViewModel)sr.Deserialize(pa.Response_s, typeof(EducationInfoViewModel));
                lstEducationInfo.Add(educationInfo);
            }
            if (lstEducationInfo.Count == 0)
            {
                lstEducationInfo.Add(new EducationInfoViewModel() { SchoolName = null, Province = null, Nation = null, EndYear = null, Degree = null, BeginYear = null });
            }
            return PartialView(lstEducationInfo);
        }

        [HttpPost]
        [RequireUserLogin()]
        public PartialViewResult SavingEducationInfo(List<EducationInfoViewModel> lstEducationInfo)
        {
            //Undone : Xoa bot education
            if (ModelState.IsValid)
            {
                ProfileAttributeType profileAttributType = ProfileAttributeType.SingleByAttributeType(EnumAttributeType.EducationInfo.ToString());
                Profile profile = Profile.Single(RequireUserLogin.LoginUser.AccountID_u);
                //Xoa toan bo education hien tai
                ProfileAttribute.Delete(profile.ProfileID_u, profileAttributType.ProfileAttributeTypeID_u);
                //Them moi
                ProfileAttribute newProfileAttribute;
                List<ProfileAttribute> lstProfileAttribute = new List<ProfileAttribute>();
                JavaScriptSerializer sr = new JavaScriptSerializer();
                foreach (EducationInfoViewModel eivm in lstEducationInfo)
                {
                    newProfileAttribute = new ProfileAttribute();
                    newProfileAttribute.ProfileAttributeTypeID_u = profileAttributType.ProfileAttributeTypeID_u;
                    newProfileAttribute.ProfileID_u = profile.ProfileID_u;
                    newProfileAttribute.ProfileAttributeID_u = Guid.NewGuid();
                    newProfileAttribute.Response_s = sr.Serialize(eivm);
                    newProfileAttribute.CreateDate_dt = DateTime.Now;
                    lstProfileAttribute.Add(newProfileAttribute);
                }
                if (ProfileAttribute.Add(lstProfileAttribute) > 0)
                {
                    ViewBag.Success = true;
                    return PartialView("EducationInfo", lstEducationInfo);
                }
                else
                {
                    ViewBag.Success = false;
                }
            }
            return PartialView("EducationInfo", lstEducationInfo);
        }

        [RequireUserLogin()]
        public PartialViewResult AddInfomation(string typeName, int index)
        {
            switch (typeName)
            {
                case "EducationInfo":
                    PartialViewResult Educationpvr = PartialView("DetailsEducationInfo");
                    Educationpvr.ViewBag.LastIndex = index;
                    return Educationpvr;
                case "OccupationInfo":
                    PartialViewResult Occupationpvr = PartialView("DetailsOccupationInfo");
                    Occupationpvr.ViewBag.LastIndex = index;
                    return Occupationpvr;
                case "AccomodationInfo":
                    PartialViewResult Accomodationpvr = PartialView("DetailsAccomodationInfo");
                    Accomodationpvr.ViewBag.LastIndex = index;
                    return Accomodationpvr;

            }
            return null;
        }

        [RequireUserLogin()]
        public PartialViewResult OccupationInfo()
        {
            Account user = (Account)LibSession.Get(Constants.ACCOUNT_LOGIN);
            Profile profile = Profile.Single(user.AccountID_u);
            List<ProfileAttribute> lstProfileAttribute = ProfileAttribute.SelectByProfileIdAndAttributeType(profile.ProfileID_u, EnumAttributeType.OccupationInfo.ToString());
            List<OccupationInfoViewModel> lstOccupationInfo = new List<OccupationInfoViewModel>();
            OccupationInfoViewModel occupationInfo;
            foreach (ProfileAttribute pa in lstProfileAttribute)
            {
                JavaScriptSerializer sr = new JavaScriptSerializer();
                occupationInfo = (OccupationInfoViewModel)sr.Deserialize(pa.Response_s, typeof(OccupationInfoViewModel));
                lstOccupationInfo.Add(occupationInfo);
            }
            if (lstOccupationInfo.Count == 0)
            {
                lstOccupationInfo.Add(new OccupationInfoViewModel());
            }
            return PartialView(lstOccupationInfo);
        }

        [HttpPost]
        [RequireUserLogin()]
        public PartialViewResult SavingOccupationInfo(List<OccupationInfoViewModel> lstOccupationInfo)
        {
            //Undone : Xoa bot OccupationInfo
            if (ModelState.IsValid)
            {
                ProfileAttributeType profileAttributType = ProfileAttributeType.SingleByAttributeType(EnumAttributeType.OccupationInfo.ToString());
                Profile profile = Profile.Single(RequireUserLogin.LoginUser.AccountID_u);
                //Xoa toan bo education hien tai
                ProfileAttribute.Delete(profile.ProfileID_u, profileAttributType.ProfileAttributeTypeID_u);
                //Them moi
                ProfileAttribute newProfileAttribute;
                List<ProfileAttribute> lstProfileAttribute = new List<ProfileAttribute>();
                JavaScriptSerializer sr = new JavaScriptSerializer();
                foreach (OccupationInfoViewModel oivm in lstOccupationInfo)
                {
                    newProfileAttribute = new ProfileAttribute();
                    newProfileAttribute.ProfileAttributeTypeID_u = profileAttributType.ProfileAttributeTypeID_u;
                    newProfileAttribute.ProfileID_u = profile.ProfileID_u;
                    newProfileAttribute.ProfileAttributeID_u = Guid.NewGuid();
                    newProfileAttribute.Response_s = sr.Serialize(oivm);
                    newProfileAttribute.CreateDate_dt = DateTime.Now;

                    lstProfileAttribute.Add(newProfileAttribute);
                }
                if (ProfileAttribute.Add(lstProfileAttribute) > 0)
                {
                    ViewBag.Success = true;
                    return PartialView("OccupationInfo", lstOccupationInfo);
                }
                else
                {
                    ViewBag.Success = false;
                }
            }
            return PartialView("OccupationInfo", lstOccupationInfo);
        }

        [RequireUserLogin()]
        public PartialViewResult AccomodationInfo()
        {
            Account user = (Account)LibSession.Get(Constants.ACCOUNT_LOGIN);
            Profile profile = Profile.Single(user.AccountID_u);
            List<ProfileAttribute> lstProfileAttribute = ProfileAttribute.SelectByProfileIdAndAttributeType(profile.ProfileID_u, EnumAttributeType.AccomodationInfo.ToString());
            List<AccomodationInfoViewModel> lstAccomodationInfo = new List<AccomodationInfoViewModel>();
            AccomodationInfoViewModel accomodationInfo;
            foreach (ProfileAttribute pa in lstProfileAttribute)
            {
                JavaScriptSerializer sr = new JavaScriptSerializer();
                accomodationInfo = (AccomodationInfoViewModel)sr.Deserialize(pa.Response_s, typeof(AccomodationInfoViewModel));
                lstAccomodationInfo.Add(accomodationInfo);
            }
            if (lstAccomodationInfo.Count == 0)
            {
                lstAccomodationInfo.Add(new AccomodationInfoViewModel());
            }
            return PartialView(lstAccomodationInfo);

        }

        [RequireUserLogin()]
        public PartialViewResult SavingAccomodationInfo(List<AccomodationInfoViewModel> lstAccomodationInfo)
        {
            //Undone : Xoa bot OccupationInfo
            if (ModelState.IsValid)
            {
                ProfileAttributeType profileAttributType = ProfileAttributeType.SingleByAttributeType(EnumAttributeType.AccomodationInfo.ToString());
                Profile profile = Profile.Single(RequireUserLogin.LoginUser.AccountID_u);
                //Xoa toan bo education hien tai
                ProfileAttribute.Delete(profile.ProfileID_u, profileAttributType.ProfileAttributeTypeID_u);
                //Them moi
                ProfileAttribute newProfileAttribute;
                List<ProfileAttribute> lstProfileAttribute = new List<ProfileAttribute>();
                JavaScriptSerializer sr = new JavaScriptSerializer();
                foreach (AccomodationInfoViewModel aivm in lstAccomodationInfo)
                {
                    newProfileAttribute = new ProfileAttribute();
                    newProfileAttribute.ProfileAttributeTypeID_u = profileAttributType.ProfileAttributeTypeID_u;
                    newProfileAttribute.ProfileID_u = profile.ProfileID_u;
                    newProfileAttribute.ProfileAttributeID_u = Guid.NewGuid();
                    newProfileAttribute.Response_s = sr.Serialize(aivm);
                    newProfileAttribute.CreateDate_dt = DateTime.Now;
                    lstProfileAttribute.Add(newProfileAttribute);
                }
                if (ProfileAttribute.Add(lstProfileAttribute) > 0)
                {
                    ViewBag.Success = true;
                    return PartialView("AccomodationInfo", lstAccomodationInfo);
                }
                else
                {
                    ViewBag.Success = false;
                }
            }
            return PartialView("AccomodationInfo", lstAccomodationInfo);
        }

        [RequireUserLogin()]
        public PartialViewResult InterestInfo()
        {
            Account user = (Account)LibSession.Get(Constants.ACCOUNT_LOGIN);
            Profile profile = Profile.Single(user.AccountID_u);
            List<ProfileAttribute> lstProfileAttribute = ProfileAttribute.SelectByProfileIdAndAttributeType(profile.ProfileID_u, EnumAttributeType.InterestInfo.ToString());

            InterestInfoViewModel interestInfo = new InterestInfoViewModel();
            if (lstProfileAttribute.Count != 0)
            {
                interestInfo.Interest = lstProfileAttribute[0].Response_s;
            }

            return PartialView(interestInfo);
        }

        [RequireUserLogin()]
        public PartialViewResult SavingInterestInfo(InterestInfoViewModel interestInfo)
        {
            //Undone : cac ki tu < > & <br> chua xu ly javascript
            if (ModelState.IsValid)
            {
                ProfileAttributeType profileAttributType = ProfileAttributeType.SingleByAttributeType(EnumAttributeType.InterestInfo.ToString());
                Profile profile = Profile.Single(RequireUserLogin.LoginUser.AccountID_u);
                //Xoa toan bo education hien tai
                ProfileAttribute.Delete(profile.ProfileID_u, profileAttributType.ProfileAttributeTypeID_u);
                //Them moi
                ProfileAttribute newProfileAttribute;
                JavaScriptSerializer sr = new JavaScriptSerializer();
                newProfileAttribute = new ProfileAttribute();
                newProfileAttribute.ProfileAttributeTypeID_u = profileAttributType.ProfileAttributeTypeID_u;
                newProfileAttribute.ProfileID_u = profile.ProfileID_u;
                newProfileAttribute.ProfileAttributeID_u = Guid.NewGuid();
                newProfileAttribute.Response_s = interestInfo.Interest;
                newProfileAttribute.CreateDate_dt = DateTime.Now;

                if (ProfileAttribute.Add(newProfileAttribute) > 0)
                {
                    ViewBag.Success = true;
                    return PartialView("InterestInfo", interestInfo);
                }
                else
                {
                    ViewBag.Success = false;
                }
            }
            return PartialView("InterestInfo", interestInfo);
        }

        [RequireUserLogin()]
        public ActionResult ChangeAvatar()
        {
            Account currentUser = RequireUserLogin.LoginUser;
            if (currentUser.Avatar_s == null)
            {
                ViewBag.ImageSource = "";
            }
            else
            {
                ViewBag.ImageSource = currentUser.Avatar_s;
            }
            return View();
        }

        public ActionResult ChangeAvatarError(string error)
        {
            Account currentUser = RequireUserLogin.LoginUser;
            if (currentUser.Avatar_s == null)
            {
                ViewBag.ImageSource = "";
            }
            else
            {
                ViewBag.ImageSource = currentUser.Avatar_s;
            }
            ViewBag.Error = error;
            return View("ChangeAvatar");
        }

        [RequireUserLogin()]
        [HttpPost]
        public ActionResult ChangeAvatar(HttpPostedFileBase fileAvatar)
        {
            Account currentUser = RequireUserLogin.LoginUser;
            bool error = false;
            if (fileAvatar == null)
            {
                error = true;
                return RedirectToAction("ChangeAvatarError", new { @error = "Chưa chọn file hình"});
            }
            if (fileAvatar.ContentType.Contains("image"))
            {
                WebImage wim = new WebImage(fileAvatar.InputStream);
                if (wim.Width > 400)
                {
                    wim.Resize(400, (int)((float)400 * wim.Height / wim.Width), preserveAspectRatio: true);
                }
                //if (wim.Height > 400)
                //{
                //    wim.Resize((int)((float)400 * wim.Width / wim.Height), 400, preserveAspectRatio: true);
                //}

                if (wim.Width < 180)
                {
                    error = true;
                    return RedirectToAction("ChangeAvatarError", new { @error = "Hãy chọn hình có chiều rộng lớn hơn hoặc bằng 180px" });
                }

                //Neu file hop le, Luu xuong thu muc cua nguoi dung /Files/Images/Avatar/7b9d093d-5a22-4b0d-b8c3-158a20a58e3d/ tenfile.type
                //Luu file goc voi kich thuoc co chinh sua 420px original; Luu file kich thuoc Small , Large
                string virtualPath = @"/Files/Images/Avatar/" + currentUser.AccountID_u.ToString();
                string absoluteFolderPath = Server.MapPath(virtualPath);
                if (!Directory.Exists(absoluteFolderPath))
                {
                    Directory.CreateDirectory(absoluteFolderPath.Replace('/', '\\'));
                }

                string formatPath = absoluteFolderPath + "\\";
                string type = fileAvatar.ContentType;
                type = type.Substring(type.LastIndexOf('/') + 1);
                if (type == "pjpeg")
                {
                    type = "jpeg";
                }
                else
                {
                    if (type == "gif")
                    {
                        type = "gif";
                    }
                    else
                    {
                        type = "png";
                    }
                }
                //Ondone transaction
                Guid g = Guid.NewGuid();
                Account.UpdateAvatar(currentUser.AccountID_u, virtualPath + "/" + g.ToString() + "_Original." + type);
                LibSession.Set(Constants.ACCOUNT_LOGIN, currentUser);
                //LibSession.Remove(Constants.ACCOUNT_LOGIN);
                //LibSession.Set(Constants.ACCOUNT_LOGIN, currentUser);

                RequireUserLogin.LoginUser.Avatar_s = virtualPath + "/" + g.ToString() + "_Original." + type;
                //Luu file goc
                wim.Save(formatPath + g.ToString() + "_Original", imageFormat: type);
                //Luu file Larg
                wim.Clone().Resize(180, 180 * wim.Height / wim.Width, preserveAspectRatio: true)
                    .Save(formatPath + g.ToString() + "_Large", imageFormat: type);
                wim.Clone().Resize(50, 50 * wim.Height / wim.Width, preserveAspectRatio: true)
                             .Save(formatPath + g.ToString() + "_Small", imageFormat: type);

                DirectoryInfo dir = new DirectoryInfo(formatPath);
                FileInfo[] fis = dir.GetFiles();
                foreach (FileInfo fi in fis)
                {
                    if (!fi.Name.Contains(g.ToString()))
                    {
                        fi.Delete();
                    }
                }
                ViewBag.ImageSource = virtualPath + "/" + g.ToString() + "_Original." + type;
                ViewBag.WebImage = wim;

            }
            else
            {
                ViewBag.Error = "File không hợp lệ";
                error = true;
                return RedirectToAction("ChangeAvatarError", new { @error = "Bạn phải đăng file hình ảnh" });
            }
            if (error)
            {
                if (currentUser.Avatar_s == null)
                {
                    ViewBag.ImageSource = "";
                }
                else
                {
                    ViewBag.ImageSource = currentUser.Avatar_s;
                }
            }
            return View("ChangeAvatar");
        }

        [RequireUserLogin()]
        [HttpPost]
        public string SaveAvatarEditing(int top, int right, int bottom, int left, string sizeType)
        {
            if (sizeType != "Small" && sizeType != "Large")
            {
                return "unsuccess";
            }
            if (top < 0 || right < 0 || bottom < 0 || left < 0)
            {
                return "unsuccess";
            }
            Account currentUser = RequireUserLogin.LoginUser;
            Guid g = Guid.NewGuid();
            string newGuid = g.ToString();
            string originalFileName = currentUser.Avatar_s.Substring(currentUser.Avatar_s.LastIndexOf("/") + 1);
            string oldGuid = originalFileName.Substring(0, originalFileName.LastIndexOf("_"));
            int resultUpdate = Account.UpdateAvatar(currentUser.AccountID_u, currentUser.Avatar_s.Replace(oldGuid, g.ToString()));
            if (resultUpdate != 1)
            {
                return "unsucess";
            }
            currentUser.Avatar_s = currentUser.Avatar_s.Replace(oldGuid, newGuid);
            string virtualPath = @"/Files/Images/Avatar/" + currentUser.AccountID_u.ToString() + "/";
            string absoluteFolderPath = Server.MapPath(virtualPath);

            if (!Directory.Exists(absoluteFolderPath))
            {
                Directory.CreateDirectory(absoluteFolderPath.Replace('/', '\\'));
            }
            DirectoryInfo dir = new DirectoryInfo(absoluteFolderPath);

            Account.UpdateAvatar(currentUser.AccountID_u, currentUser.Avatar_s.Replace(oldGuid, newGuid));
            //LibSession.Set(Constants.ACCOUNT_LOGIN, currentUser);
            FileInfo[] fis = dir.GetFiles();
            string extension = "";
            foreach (FileInfo fi in fis)
            {
                if (fi.Name.Contains(sizeType))
                {
                    extension = fi.Extension;
                    fi.Delete();

                }
                else
                {
                    //phan cuoi cua ten file
                    fi.MoveTo(fi.FullName.Replace(oldGuid, newGuid));
                }
            }

            WebImage wim = new WebImage(Server.MapPath(currentUser.Avatar_s));
            float ratio = (float)wim.Height / wim.Width;
            if (sizeType == "Large")
            {
                wim = wim.Crop(top, left, wim.Height - bottom, wim.Width - right).Resize(180, (int)(180 * ratio), preserveAspectRatio: true);
            }
            else
            {
                wim = wim.Crop(top, left, wim.Height - bottom, wim.Width - right).Resize(50, 50);

            }
            wim.Save(absoluteFolderPath + newGuid + "_" + sizeType + extension);
            return "success";
        }
    }
}
